package top.continew.admin.generator.controller;

import top.continew.admin.generator.model.query.TaskListCustomQuery;
import top.continew.admin.generator.model.req.TransferHandleReq;
import top.continew.admin.system.model.resp.MyTaskRes;
import top.continew.starter.extension.crud.enums.Api;

import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.continew.starter.extension.crud.model.resp.PageResp;
import top.continew.starter.web.model.R;
import jakarta.servlet.http.HttpServletResponse;

import top.continew.starter.extension.crud.annotation.CrudRequestMapping;
import top.continew.admin.common.controller.BaseController;
import top.continew.admin.generator.model.query.TaskListQuery;
import top.continew.admin.generator.model.req.TaskListReq;
import top.continew.admin.generator.model.resp.TaskListDetailResp;
import top.continew.admin.generator.model.resp.TaskListResp;
import top.continew.admin.generator.service.TaskListService;
import top.continew.admin.system.model.resp.ExportTaskResp;
import top.continew.admin.system.service.ExportTaskService;

import java.util.List;
import java.util.Map;

/**
 * 任务管理管理 API
 *
 * @author jiangjun
 * @since 2025/06/20 17:28
 */
@Tag(name = "任务管理管理 API")
@RestController
@CrudRequestMapping(value = "/generator/taskList", api = {Api.PAGE, Api.GET, Api.CREATE, Api.UPDATE, Api.DELETE, Api.EXPORT})
public class TaskListController extends BaseController<TaskListService, TaskListResp, TaskListDetailResp, TaskListQuery, TaskListReq> {

    private final ExportTaskService exportTaskService;

    public TaskListController(ExportTaskService exportTaskService) {
        this.exportTaskService = exportTaskService;
    }



    @Operation(summary = "导入Excel")
    @PostMapping("/import")
    public R<String> importExcel(@RequestParam("file") MultipartFile file) {
        return R.ok(baseService.importExcel(file));
    }



    @Operation(summary = "分页查询")
    @PostMapping("/myPageQuery")
    public PageResp<MyTaskRes> myPageQuery(@RequestBody TaskListCustomQuery c) {
        return baseService.myPageQuery(c);
    }

    @Operation(summary = "导出Excel")
    @GetMapping("/myExport")
    public void myExport(TaskListCustomQuery query, HttpServletResponse response) {
        baseService.myExport(query, response);
    }

    @Operation(summary = "异步导出Excel")
    @PostMapping("/asyncExport")
    public R<String> asyncExport(@RequestBody TaskListCustomQuery query) {
        String taskId = baseService.asyncExport(query);
        return R.ok(taskId, "导出任务已提交");
    }

    @Operation(summary = "获取导出任务列表")
    @GetMapping("/exportTasks")
    public R<List<ExportTaskResp>> getExportTasks() {
        return R.ok(baseService.getExportTasks());
    }

    @Operation(summary = "获取导出任务详情")
    @GetMapping("/exportTask/{taskId}")
    public R<ExportTaskResp> getExportTask(@PathVariable String taskId) {
        return R.ok(baseService.getExportTask(taskId));
    }

    @Operation(summary = "下载导出文件")
    @GetMapping("/download/{taskId}")
    public void downloadExportFile(@PathVariable String taskId, HttpServletResponse response) {
        baseService.downloadExportFile(taskId, response);
    }

    @Operation(summary = "工作量统计")
    @GetMapping("/workloadStats")
    public R<Object> getWorkloadStats(
            @RequestParam(required = false) String provinceName,
            @RequestParam(required = false) String handler,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        return R.ok(baseService.getWorkloadStats(provinceName, handler, startDate, endDate));
    }

    @Operation(summary = "获取筛选选项")
    @GetMapping("/filterOptions")
    public R<Object> getFilterOptions(
            @RequestParam(required = false) String categoryName,
            @RequestParam(required = false) String spec,
            @RequestParam(required = false) String provinceName,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        return R.ok(baseService.getFilterOptions(categoryName, spec, provinceName, startDate, endDate));
    }

    @Operation(summary = "获取负责人列表")
    @GetMapping("/handlers")
    public R<Object> getHandlers() {
        return R.ok(baseService.getHandlers());
    }

    @Operation(summary = "根据省区获取负责人")
    @GetMapping("/handlersByProvince")
    public R<Object> getHandlersByProvince(@RequestParam String provinceName) {
        return R.ok(baseService.getHandlersByProvince(provinceName));
    }

    @Operation(summary = "批量修改负责人")
    @PostMapping("/batchUpdateHandler")
    public R<Void> batchUpdateHandler(@RequestBody Map<String, Object> params) {
        List<String> taskIds = (List<String>) params.get("taskIds");
        Long newHandlerId = Long.valueOf(params.get("newHandlerId").toString());
        String newHandlerName = params.get("newHandlerName").toString();
        baseService.batchUpdateHandler(taskIds, newHandlerId, newHandlerName);
        return R.ok();
    }

    @Operation(summary = "查询任务分配表列表")
    @GetMapping("/{id}/assignments")
    public R<Object> getTaskAssignments(@PathVariable String id) {
        return R.ok(baseService.getTaskAssignments(id));
    }

    @Operation(summary = "修改任务分配处理人")
    @PutMapping("/assignment/{assignmentId}")
    public R<String> updateTaskAssignment(@PathVariable String assignmentId, @RequestBody Object data) {
        baseService.updateTaskAssignment(assignmentId, data);
        return R.ok("修改成功");
    }

    @Operation(summary = "获取价格分析数据")
    @GetMapping("/priceAnalysis")
    public R<Object> getPriceAnalysis(
            @RequestParam(required = false) String categoryName,
            @RequestParam(required = false) String spec,
            @RequestParam(required = false) String provinceName,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        return R.ok(baseService.getPriceAnalysis(categoryName, spec, provinceName, startDate, endDate));
    }

    @Operation(summary = "删除任务及其分配记录")
    @DeleteMapping("/deleteWithAssignments")
    public R<String> deleteTaskWithAssignments(@RequestBody Map<String, Object> params) {
        @SuppressWarnings("unchecked")
        List<Long> ids = (List<Long>) params.get("ids");
        boolean result = baseService.deleteTaskWithAssignments(ids);
        return result ? R.ok("删除成功") : R.fail();
    }

    @Operation(summary = "获取导入批次列表")
    @GetMapping("/batches")
    public R<Object> getBatches() {
        return R.ok(baseService.getBatches());
    }

    @Operation(summary = "获取搜索选项")
    @GetMapping("/searchOptions")
    public R<Object> getSearchOptions() {
        return R.ok(baseService.getSearchOptions());
    }


    @Operation(summary = "处理转派")
    @PostMapping("/handleTransfer")
    public R<String> handleTransfer(@RequestBody TransferHandleReq req) {
        baseService.handleTransfer(req);
        return R.ok("处理成功");
    }

    @Operation(summary = "获取转派链条")
    @GetMapping("/transferChain/{taskId}")
    public R<Object> getTransferChain(@PathVariable Long taskId) {
        return R.ok(baseService.getTransferChain(taskId));
    }

    @Operation(summary = "批量删除任务")
    @DeleteMapping("/batchDelete")
    public R<String> batchDeleteTasks(@RequestBody Map<String, Object> params) {
        @SuppressWarnings("unchecked")
        List<Long> ids = (List<Long>) params.get("ids");
        boolean result = baseService.deleteTaskWithAssignments(ids);
        return result ? R.ok("批量删除成功") : R.fail();
    }

}